<template>
  <div>
    <el-main>
      <div class="form_title">用户信息</div>
      <div class="form_content">
        <el-form
          ref="form"
          label-width="80px"
          :model="model"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="登录名称" prop="username">
                <el-input v-model="model.username" v-if="!isEdit" placeholder="请输入登录名称" />
                <el-input v-model="model.username" v-if="isEdit" readonly="readonly" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="!isEdit">
            <el-col :span="24">
              <el-form-item label="登录密码" prop="password">
                <el-input
                  placeholder="请输入登录密码"
                  v-model="model.password" show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="!isEdit">
            <el-col :span="24">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  placeholder="请输入确认密码"
                  v-model="model.confirmPassword" show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="名称" prop="name">
                <el-input
                  placeholder="请输入名称"
                  v-model="model.name"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="电话号码" prop="phone">
                <el-input
                  placeholder="请输入电话号码"
                  v-model="model.phone"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  placeholder="请输入邮箱"
                  v-model="model.email"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="排序" prop="sortIndex">
                <el-input-number v-model="model.sortIndex" :min="1" :max="1000" placeholder="请输入排序"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" :rows="5" v-model="model.remark" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="form_title">角色信息</div>
      <div class="form_content">
        <el-table
          ref="table"
          :data="roleTable"
          :border="true"
          style="width: 100%"
          size="small"
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="name"
            label="名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            :formatter="statusFormatter"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            :formatter="datetimeFormatter"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>
    </el-main>
    <el-footer>
      <el-button
        icon="el-icon-close"
        size="small"
        @click="$router.go(-1)"
      >取消</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-check"
        size="small"
        @click="handleSave"
      >保存</el-button
      >
    </el-footer>
  </div>
</template>

<script>
  import {searchRole} from "@/api/system/role";
  import {insertUser,updateUser,viewUser} from "@/api/system/user";
  import {Status} from "@/utils/constant/status";
  import {parseTime} from "@/utils/common";
  import {ApiError} from "@/utils/errors";

  export default {
    data() {
      return {
        isEdit: false,
        model: {
          username: null,
          password: null,
          confirmPassword: null,
          name: null,
          phone: null,
          email: null,
          sortIndex: 1,
          remark: null
        },
        rules: {
          username: [{ required: true, message: "登录名称必须填写", trigger: "blur" }],
          // password: [{ required: true, message: "登录密码必须填写", trigger: "blur" }],
          // confirmPassword: [{ required: true, message: "确认密码必须填写", trigger: "blur" }],
          name: [{ required: true, message: "姓名必须填写", trigger: "blur" }],
          phone: [{ required: true, message: "电话号码必须填写", trigger: "blur" }],
          email: [{ required: true, message: "邮箱必须填写", trigger: "blur" }],
          sortIndex: [{ required: true, message: "排序必须填写", trigger: "blur" }]
        },
        roleTable: [],
        roleKey: null,
        multipleSelection: []
      }
    },
    created() {
      const id = this.$route.query.id;
      if(id){
        this.isEdit = true;
        this.get(id);
      }else{
        this.getRole();
      }
    },
    methods: {
      get(id){
        const that = this;
        const params = {id:id};
        viewUser(params).then(res => {
          if (res.status == 200) {
            if (!res.data.success) {
              return this.$message.error(ApiError.msg(res.data.message));
            }
            that.model.id = res.data.data.id;
            that.model.username = res.data.data.username;
            that.model.name = res.data.data.name;
            that.model.phone = res.data.data.phone;
            that.model.email = res.data.data.email;
            that.model.sortIndex = res.data.data.sortIndex;
            that.model.remark = res.data.data.remark;
            that.getRole(res.data.data["roles"]);
          }
        });
      },
      getRole(roles) {
        const that = this;
        searchRole().then(res => {
          if (res.status == 200) {
            if (!res.data.success) {
              return this.$message.error(ApiError.msg(res.data.message));
            }
            const data = res.data.data;
            that.roleTable = data;
            if(roles){
              that.roleKey = {};
              for(let i=0;i<data.length;i++){
                that.roleKey[data[i].id] = data[i];
              }
              that.$nextTick(()=>{
                for(let i=0;i<roles.length;i++){
                  this.$refs.table.toggleRowSelection(that.roleKey[roles[i].id]);
                }
              });
            }
          }
        });
      },
      handleSelectionChange(val){
        this.multipleSelection = val;
      },
      handleSave() {
        const that = this;
        this.$refs.form.validate(valid => {
          if (!valid) {
            return;
          }
          that.model.roleIds = [];
          for(let i=0;i<that.multipleSelection.length;i++){
            that.model.roleIds.push(that.multipleSelection[i].id);
          }
          let saveUser = insertUser;
          if (that.isEdit) {
            saveUser = updateUser;
          }
          saveUser(that.model).then(res => {
            if (res.status == 200) {
              if (!res.data.success) {
                return this.$message.error(ApiError.msg(res.data.message));
              }
              this.$message.success(this.isEdit ? "修改用户成功" : "新增用户成功");
              that.$router.go(-1);
            }
          });
        });
      },
      statusFormatter(row) {
        return Status[row.status]["name"];
      },
      datetimeFormatter(row) {
        return parseTime(row["createTime"]);
      }
    }
  }
</script>

<style lang="scss" scoped>
  .form_title {
    padding-bottom: 20px;
    font-size: 16px;
    font-weight: 700;
    color: rgba(0, 0, 0, 0.85);
  }
  .form_content {
    padding-right: 16px;
  }
  .input_suffix {
    display: inline-block;
    padding: 0 6px;
  }
  .el-divider {
    margin: 6px 0 16px;
  }
  .add_new_batch {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    height: 45px;
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    color: #8c939d;
  }
  .batch_block {
    margin-top: 16px;
  }
  .batch_block:first-child {
    margin-top: 0;
  }
  @import "@/styles/full-form";
  @import "@/styles/common-table";
</style>
